﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.TianQue.Services;
using NewRetail.Application.Core;
using NewRetail.Application.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace NewRetail.Api.Controllers.WeChatControllers
{
    /// <summary>
    /// 用于处理天阙支付回调的信息
    /// </summary>
    [NewRetailRoute("tianque-notify")]
    public class TianQueNotifyController : BaseController
    {
        #region Field
        private readonly ITianQueService _tianQueService;
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        public TianQueNotifyController(ITianQueService tianQueService, ILogger<TianQueNotifyController> logger)
        {
            _tianQueService = tianQueService;
            _logger = logger;
        }
        #endregion

        #region method

        #region 天阙支付回调相关

        #region 天阙支付回调通知
        [HttpPost]
        [Route("m-{merchantId}/messagepush")]
        public async Task<IActionResult> ReceiveMessage(
            [FromRoute(Name = "merchantId")] string merchantId,
            [FromHeader(Name = "Wechatpay-Timestamp")] string timestamp)
        {
            using var reader = new StreamReader(Request.Body, Encoding.UTF8);
            string content = await reader.ReadToEndAsync();
            _logger.LogInformation("接收到支付推送的数据：{0}", content);
            IDictionary<string, object> respData = null;

            try
            {
                bool valid = false;
                respData = UtilsHelper.DeserializeObject<Dictionary<string, object>>(content);
                var respDeepCloneData = respData.DeepClone();
                if (respData != null)
                    valid = _tianQueService.VerifyEventSignature(respData);
                
                if (!valid)
                    return new JsonResult(new { code = "verify fail", msg = "验签失败" });
                else
                {
                    //验签成功则记录
                    var result = await _tianQueService.TianQueNotifyResponseMessage(respDeepCloneData);
                    if (!result.Item1)
                        return new JsonResult(new { code = "fail", msg = "验签成功，业务异常。"+result.Item2 });
                }
            }
            catch (Exception e)
            {
                _logger.LogError(message: e.Message, exception: e);
                return new JsonResult(new { code = "error", msg = e.Message });
            }
            return new JsonResult(new { code = "success", msg = "成功" });
        }
        #endregion

        #endregion

        #endregion
    }
}
